<script setup lang="ts">
import { Right as AppNutIconRight } from '@nutui/icons-vue-taro';
import { reactive, onMounted, ref } from 'vue';
import { showLoading, showToast, navigateTo, showModal, getCurrentInstance } from '@tarojs/taro';
import ApproveProcessList from '../../approve/edit/components/approve-process-list/approve-process-list.vue';
import { QUERY_FTD_FOR_ADD_FLOW } from '/@/api/modules/flow-path/flow-path-template';
import { GOV_CAR_LIST, ADD_GOV_CAR_APPLY } from '/@/api/modules/flow-path/flow-path-gov-car';
import { SYS_DICT_REGION_QUERY } from '/@/api/modules/base/sys-dict-region';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import { FIND_ONE, SAVE, DELETE } from '/@/api/modules/flow-path/flow-path-draft';
import { CAR_APPROVE_TEMPLATE_CODE } from '/@/common/constant';
import dayjs from 'dayjs';
import { QUERY_APP_FLOW_PATH_RECORD_DETAIL } from '/@/api/modules/flow-path/flow-path';
import { SYS_ORGAN_QUERY_APP } from '/@/api/modules/base/app-sys-organ';
import { values } from 'lodash';
const params = getCurrentInstance().router?.params as {
  /**
   * 审批id
   */
  id?: string;
};

interface AreaType {
  value: number;
  text: string;
  children: AreaType[];
}
//局部
const state = reactive<{
  /**
   * 部门选择
   */
  departmentIsShow?: boolean;
  departmentList: AppSysOrgan.Dto[];
  userId?: string;
  deptId: string;
  deptName: string;
  startTime: string;
  startTimeIsShow?: boolean;
  endTime: string;
  endTimeIsShow?: boolean;
  cardNo: string;
  cardNoIsShow?: boolean;
  carList?: Array<FlowpathGovCar.GovCarDto>;
  user: string;
  userIsShow?: boolean;
  description: string;
  descIsShow?: boolean;
  useScope: string;
  useScopeIsShow?: boolean;
  areaList: AreaType[];
  target: string;
  /**
   * 审批流程配置图结构体
   */
  flowGraphAddFlow?: FlowPathTemplateApi.FlowGraph;
  templateId?: string;
  attributes?: FlowPathTemplateApi.AttributeDto[];
}>({
  departmentIsShow: false,
  departmentList: [],
  userId: '',
  deptId: '',
  deptName: '',
  startTime: '',
  startTimeIsShow: false,
  endTime: '',
  endTimeIsShow: false,
  cardNo: '',
  cardNoIsShow: false,
  user: '',
  userIsShow: false,
  description: '',
  descIsShow: false,
  useScope: '',
  useScopeIsShow: false,
  areaList: [],
  target: '',
  flowGraphAddFlow: {},
  templateId: '',
  attributes: [],
});

/**
 * 查询审批模版详情
 * @param code 审批模版code
 */
function queryDetail(code: string) {
  showLoading();
  QUERY_FTD_FOR_ADD_FLOW({ code }).then((res) => {
    state.templateId = res.flowpathTemplateDto?.id;
    state.attributes = res.flowpathTemplateDto?.attributes;
    state.flowGraphAddFlow = res.flowpathTemplateDto?.flowGraphAddFlow;

    if (params.id) {
      queryApprovedDetail(params.id);
    } else {
      queryDraft(code);
    }
  });
}

onMounted(() => {
  queryDetail(CAR_APPROVE_TEMPLATE_CODE);
  queryArea();
  queryDepartment();
  state.useScope = '浙江省-金华市-婺城区';
});

function queryDepartment() {
  SYS_ORGAN_QUERY_APP({
    comQuery: { page: 1, pageSize: 10000 },
  }).then((res) => {
    //用车部门 仅选择第三级
    if (
      res.content &&
      res.content.length > 0 &&
      res.content[0].children &&
      res.content[0].children.length > 0 &&
      res.content[0].children[0].children
    ) {
      state.departmentList = res.content[0].children[0].children;
    }
  });
}

/**
 * 选择部门
 */
function departmentConfirm({ selectedOptions }: any) {
  state.deptId = selectedOptions[0].value;
  state.deptName = selectedOptions[0].text;
  state.departmentIsShow = false;
  queryGovCarList();
}

const minDate = dayjs().subtract(1, 'year').toDate();
const maxDate = dayjs().add(1, 'year').toDate();
let currentDate1 = new Date();

const startTimeConfirm = ({ selectedValue }) => {
  const date = selectedValue.slice(0, 3).join('-');
  const time = selectedValue.slice(3).join(':');
  state.startTime = date + ' ' + time;
  currentDate1 = dayjs(state.startTime).toDate();
  state.startTimeIsShow = false;
  if (state.startTime && state.endTime) {
    queryGovCarList();
  }
};

function endTimeClick() {
  if (!state.startTime) {
    showToast({
      title: '请先选择开始日期',
      icon: 'error',
    });
    return;
  }
  state.endTimeIsShow = !state.endTimeIsShow;
}
let currentDate2 = new Date();
const endTimeConfirm = ({ selectedValue }) => {
  const date = selectedValue.slice(0, 3).join('-');
  const time = selectedValue.slice(3).join(':');
  if (dayjs(state.startTime).isAfter(dayjs(date + ' ' + time))) {
    showToast({
      title: '开始日期不能大于结束日期',
      icon: 'error',
    });
    return;
  }
  state.endTime = date + ' ' + time;
  currentDate2 = dayjs(state.endTime).toDate();
  state.endTimeIsShow = false;
  queryGovCarList();
};

function queryGovCarList() {
  const startUseTime = dayjs(state.startTime).valueOf();
  const endUseTime = dayjs(state.endTime).valueOf();
  showLoading();
  GOV_CAR_LIST({
    comQuery: { page: 1, pageSize: 1000 },
    app: 1,
    deptId: state.deptId,
    startUseTime,
    endUseTime,
  }).then((res) => {
    state.carList = res.list;
    //按车牌号文本升序排序
    state.carList?.sort((one: FlowpathGovCar.GovCarDto, two: FlowpathGovCar.GovCarDto) => {
      if (!one.plateNo || !two.plateNo) return 0;
      return one.plateNo.localeCompare(two.plateNo);
    });
  });
}

function useCarConfirm({ selectedOptions }: any) {
  const text = selectedOptions[0].text;
  state.cardNo = text;
  state.cardNoIsShow = false;
}

function cardNoClick() {
  if (!state.startTime) {
    showToast({
      title: '请先选择开始日期',
      icon: 'error',
    });
    return;
  }
  if (!state.endTime) {
    showToast({
      title: '请先选择结束用车时间',
      icon: 'error',
    });
    return;
  }
  state.cardNoIsShow = !state.cardNoIsShow;
}

function descConfirm({ selectedOptions }: any) {
  const text = selectedOptions[0].text;
  state.description = text;
  state.descIsShow = false;
}

/**
 * 查询全国区域
 */
function queryArea() {
  SYS_DICT_REGION_QUERY({}).then((res) => {
    if (res.provinceList && res.cityList && res.countyList) {
      const areaList = trans(res.provinceList, res.cityList, res.countyList);
      state.areaList = areaList;
    }
  });
}

// 转换省市区
const trans = (provinceList: object, cityList: object, countyList: object) => {
  // 城市
  const cityMap = {};
  const citys = Object.keys(cityList).map((id) => {
    cityMap[id] = [];
    return { children: cityMap[id], value: +id, text: cityList[id] };
  });

  // 区县
  Object.keys(countyList).forEach((id) => {
    const newId = Number(id);
    const cityChildren = cityMap[newId - (newId % 100)] || [];
    cityChildren.push({ children: [], value: +id, text: countyList[id] });
  });

  // 省份
  return Object.keys(provinceList).map((id) => {
    const children = citys.filter((city) => city.value - (city.value % 10000) === +id);
    return { children, value: +id, text: provinceList[id] };
  });
};

function useScopeConfirm({ selectedOptions }: any) {
  const text = `${selectedOptions[0].text}-${selectedOptions[1].text}-${selectedOptions[2].text}`;
  state.useScope = text;
  state.useScopeIsShow = false;
}

const formRef = ref();
function submit() {
  formRef.value?.validate().then(({ valid }) => {
    if (!valid) return;
    ADD_GOV_CAR_APPLY({
      plateNo: state.cardNo,
      userName: state.user,
      dept: state.deptName,
      startUseTime: dayjs(state.startTime).valueOf(),
      endUseTime: dayjs(state.endTime).valueOf(),
      desc: state.description,
      useRange: state.useScope,
      direction: state.target,
      templateCode: CAR_APPROVE_TEMPLATE_CODE,
      flowGraphAddFlow: state.flowGraphAddFlow,
    }).then((res) => {
      if (res.comResp?.code === 100) {
        clearData();
        deleteDraft(CAR_APPROVE_TEMPLATE_CODE);
        navigateTo({
          url: '/pages/car-apply/submit-success/index',
        });
      }
    });
  });
}

function clearData() {
  state.deptId = '';
  state.deptName = '';
  state.startTime = '';
  state.endTime = '';
  state.cardNo = '';
  state.user = '';
  state.description = '';
  state.useScope = '';
  state.target = '';
}

function saveDraftByRequest() {
  showLoading();
  saveDraftAttributes();
  SAVE({
    userId: state.userId,
    flowpathRecordDto: {
      templateId: state.templateId,
      templateCode: CAR_APPROVE_TEMPLATE_CODE,
      attributes: state.attributes,
    },
    flowGraphAddFlow: state.flowGraphAddFlow,
  }).then((res) => {
    if (res.comResp?.code === 100) {
      showModal({
        title: '保存草稿成功',
        showCancel: false,
        content: '下次进入申请页面可继续填写表单内容',
      });
    }
  });
}
function saveDraft() {
  if (state.userId) {
    saveDraftByRequest();
  } else {
    LOGIN_APP().then((res) => {
      state.userId = res.sysUserDto.id;
      saveDraftByRequest();
    });
  }
}

function queryDraft(code: string) {
  showLoading();
  LOGIN_APP().then((res) => {
    state.userId = res.sysUserDto.id;
    FIND_ONE({ templateCode: code, userId: state.userId }).then((res) => {
      if (res.flowpathRecordDto) {
        showModal({
          title: '继续填写',
          content: '你有未提交的内容，是否载入草稿继续填写？',
          success: function (result) {
            if (result.confirm) {
              state.attributes = res.flowpathRecordDto?.attributes;
              setDraftAttributes();
              state.flowGraphAddFlow = res.flowGraphAddFlow;
            } else if (result.cancel) {
              deleteDraft(code);
            }
          },
        });
      }
    });
  });
}

function setDraftAttributes() {
  state.attributes?.forEach((item) => {
    if (item.attributeCode === 'dept') {
      state.deptName = item.attributeValue || '';
    } else if (item.attributeCode === 'startTime') {
      state.startTime = item.attributeValue || '';
    } else if (item.attributeCode === 'startTime') {
      state.startTime = item.attributeValue || '';
    } else if (item.attributeCode === 'endTime') {
      state.endTime = item.attributeValue || '';
    } else if (item.attributeCode === 'plateNo') {
      state.cardNo = item.attributeValue || '';
    } else if (item.attributeCode === 'person') {
      state.user = item.attributeValue || '';
    } else if (item.attributeCode === 'desc') {
      state.description = item.attributeValue || '';
    } else if (item.attributeCode === 'address') {
      state.useScope = item.attributeValue || '';
    } else if (item.attributeCode === 'destination') {
      state.target = item.attributeValue || '';
    }
  });
}

function saveDraftAttributes() {
  state.attributes?.forEach((item) => {
    if (item.attributeCode === 'dept') {
      item.attributeValue = state.deptName;
    } else if (item.attributeCode === 'startTime') {
      item.attributeValue = state.startTime;
    } else if (item.attributeCode === 'startTime') {
      item.attributeValue = state.startTime;
    } else if (item.attributeCode === 'endTime') {
      item.attributeValue = state.endTime;
    } else if (item.attributeCode === 'plateNo') {
      item.attributeValue = state.cardNo;
    } else if (item.attributeCode === 'person') {
      item.attributeValue = state.user;
    } else if (item.attributeCode === 'desc') {
      item.attributeValue = state.description;
    } else if (item.attributeCode === 'address') {
      item.attributeValue = state.useScope;
    } else if (item.attributeCode === 'destination') {
      item.attributeValue = state.target;
    }
  });
}
function deleteDraft(code: string) {
  DELETE({ templateCode: code, userId: state.userId });
}

/**
 * @function 获取审批详情
 */
function queryApprovedDetail(id: string) {
  showLoading();
  QUERY_APP_FLOW_PATH_RECORD_DETAIL({ id }).then((res) => {
    state.attributes = res.flowpathRecordDto?.attributes;
    setDraftAttributes();
  });
}
</script>

<template>
  <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
    <view class="car-apply-edit__wrapper">
      <nut-form ref="formRef" v-model="state">
        <nut-form-item
          label="用车部门"
          required
          prop="deptName"
          :label-width="120"
          :rules="[{ required: true, message: '请选择部门' }]"
        >
          <view
            class="car-apply-edit__left"
            @click="state.departmentIsShow = !state.departmentIsShow"
          >
            <text>{{ state.deptName || '请选择部门' }}</text>
            <app-nut-icon-right />
          </view>
        </nut-form-item>
        <nut-form-item
          label="开始用车时间"
          required
          prop="startTime"
          :label-width="120"
          :rules="[{ required: true, message: '请选择开始用车时间' }]"
        >
          <view
            class="car-apply-edit__left"
            @click="state.startTimeIsShow = !state.startTimeIsShow"
          >
            <text>{{ state.startTime || '请选择开始用车时间' }}</text>
            <app-nut-icon-right />
          </view>
        </nut-form-item>
        <nut-form-item
          label="结束用车时间"
          required
          prop="endTime"
          :label-width="120"
          :rules="[{ required: true, message: '请选择结束用车时间' }]"
        >
          <view class="car-apply-edit__left" @click="endTimeClick()">
            <text>{{ state.endTime || '请选择结束用车时间' }}</text>
            <app-nut-icon-right />
          </view>
        </nut-form-item>
        <nut-form-item
          label="车牌号"
          required
          prop="cardNo"
          :label-width="120"
          :rules="[{ required: true, message: '请选择车牌号' }]"
        >
          <view class="car-apply-edit__left" @click="cardNoClick()">
            <text>{{ state.cardNo || '请选择车牌号' }}</text>
            <app-nut-icon-right />
          </view>
        </nut-form-item>
        <nut-form-item
          label="用车人"
          required
          prop="user"
          :label-width="120"
          :rules="[{ required: true, message: '请填写用车人' }]"
        >
          <view class="car-apply-edit__left" @click="state.userIsShow = !state.userIsShow">
            <text>{{ state.user || '请选择用车人' }}</text>
            <app-nut-icon-right />
          </view>
        </nut-form-item>
        <nut-form-item
          label="用车说明"
          required
          prop="description"
          :label-width="120"
          :rules="[{ required: true, message: '用车说明' }]"
        >
          <view class="car-apply-edit__left" @click="state.descIsShow = !state.descIsShow">
            <text>{{ state.description || '请选择用车说明' }}</text>
            <app-nut-icon-right />
          </view>
        </nut-form-item>
        <nut-form-item
          label="用车范围"
          required
          prop="useScope"
          :label-width="120"
          :rules="[{ required: true, message: '请选择用车范围' }]"
        >
          <view class="car-apply-edit__left" @click="state.useScopeIsShow = !state.useScopeIsShow">
            <text>{{ state.useScope || '请选择用车范围' }}</text>
            <app-nut-icon-right />
          </view>
        </nut-form-item>
        <nut-form-item
          label="具体目的地"
          required
          prop="target"
          :label-width="120"
          :rules="[{ required: true, message: '请填写具体目的地' }]"
        >
          <nut-input
            placeholder="请填写具体目的地"
            type="text"
            input-align="right"
            v-model="state.target"
            :border="false"
          />
        </nut-form-item>
      </nut-form>
      <approve-process-list
        v-if="state.flowGraphAddFlow && Object.keys(state.flowGraphAddFlow).length > 0"
        :flow-graph-add-flow="state.flowGraphAddFlow"
      />
    </view>
  </scroll-view>
  <view class="car-apply-edit__footer">
    <nut-button class="car-apply-edit__footer-btn" color="#bbb" @click="saveDraft()"
      >存草稿</nut-button
    >
    <nut-button class="car-apply-edit__footer-btn" type="info" @click="submit()">提交</nut-button>
  </view>
  <nut-popup position="bottom" v-model:visible="state.departmentIsShow">
    <nut-picker
      :columns="
        state.departmentList?.map((item) => {
          return {
            text: item.name,
            value: item.id,
          };
        })
      "
      title="选择部门"
      @close="state.departmentIsShow = false"
      @confirm="departmentConfirm"
      @cancel="state.departmentIsShow = false"
    />
  </nut-popup>

  <nut-popup position="bottom" v-model:visible="state.startTimeIsShow">
    <nut-date-picker
      :model-value="currentDate1"
      :min-date="minDate"
      :max-date="maxDate"
      :minute-step="30"
      type="datetime"
      :is-show-chinese="true"
      @confirm="startTimeConfirm"
      @cancel="state.startTimeIsShow = false"
    />
  </nut-popup>
  <nut-popup position="bottom" v-model:visible="state.endTimeIsShow">
    <nut-date-picker
      :model-value="currentDate2"
      :min-date="minDate"
      :max-date="maxDate"
      :minute-step="30"
      type="datetime"
      :is-show-chinese="true"
      @confirm="endTimeConfirm"
      @cancel="state.endTimeIsShow = false"
    />
  </nut-popup>

  <nut-popup position="bottom" v-model:visible="state.cardNoIsShow">
    <nut-picker
      :columns="
        state.carList?.map((item) => {
          return {
            text: item.plateNo,
            value: item.id,
          };
        })
      "
      title="选择用车"
      @close="state.cardNoIsShow = false"
      @confirm="useCarConfirm"
      @cancel="state.cardNoIsShow = false"
    />
  </nut-popup>
  <app-user-list-popup
    v-model="state.userIsShow"
    title="用车人"
    @on-selected="(user: AppSysUser.Dto) => {
        state.user = user.name || '';
      }"
  />
  <nut-popup position="bottom" v-model:visible="state.descIsShow">
    <nut-picker
      :columns="[
        { text: '执法办案', values: '执法办案' },
        { text: '出差', values: '出差' },
        { text: '维修', values: '维修' },
      ]"
      title="选择用车说明"
      @close="state.descIsShow = false"
      @confirm="descConfirm"
      @cancel="state.descIsShow = false"
    />
  </nut-popup>
  <nut-popup position="bottom" v-model:visible="state.useScopeIsShow">
    <nut-picker
      :columns="state.areaList"
      title="选择用车范围"
      @close="state.useScopeIsShow = false"
      @confirm="useScopeConfirm"
      @cancel="state.useScopeIsShow = false"
    />
  </nut-popup>
</template>
<style lang="scss">
.car-apply-edit {
  &__wrapper {
    padding: 20px 20px;
  }
  &__footer {
    padding: 20px 20px;
    background-color: #fff;
    display: flex;
  }
  &__footer-status {
    padding: 20px 20px;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #999;
  }

  &__footer-btn {
    flex: 1;
    margin: 0 10px !important;
  }
  &__left {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
